<?php
require_once __DIR__ . '/../config/database.php';

/**
 * 数据库安装脚本
 */
class Installer {
    private $db;

    public function __construct() {
        $this->connect();
    }

    /**
     * 连接数据库
     */
    private function connect() {
        $this->db = new mysqli(
            DatabaseConfig::DB_HOST,
            DatabaseConfig::DB_USER,
            DatabaseConfig::DB_PASS
        );

        if ($this->db->connect_error) {
            die("数据库连接失败: " . $this->db->connect_error);
        }

        $this->db->set_charset(DatabaseConfig::DB_CHARSET);
    }

    /**
     * 创建数据库
     */
    public function createDatabase() {
        $sql = "CREATE DATABASE IF NOT EXISTS " . DatabaseConfig::DB_NAME . " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
        
        if ($this->db->query($sql)) {
            echo "数据库创建成功\n";
            $this->db->select_db(DatabaseConfig::DB_NAME);
            return true;
        } else {
            echo "数据库创建失败: " . $this->db->error . "\n";
            return false;
        }
    }

    /**
     * 创建数据表
     */
    public function createTables() {
        $tables = $this->getTableSchemas();
        
        foreach ($tables as $tableName => $sql) {
            if ($this->db->query($sql)) {
                echo "数据表 {$tableName} 创建成功\n";
            } else {
                echo "数据表 {$tableName} 创建失败: " . $this->db->error . "\n";
                return false;
            }
        }
        
        return true;
    }

    /**
     * 获取表结构
     */
    private function getTableSchemas() {
        return [
            'products' => "
                CREATE TABLE IF NOT EXISTS products (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(255) NOT NULL,
                    description TEXT,
                    price DECIMAL(10,2) NOT NULL,
                    stock INT DEFAULT 0,
                    image VARCHAR(500),
                    status TINYINT DEFAULT 1,
                    created_at DATETIME,
                    updated_at DATETIME,
                    INDEX idx_status (status),
                    INDEX idx_created (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'cdks' => "
                CREATE TABLE IF NOT EXISTS cdks (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    cdk_code VARCHAR(50) NOT NULL UNIQUE,
                    product_id INT NOT NULL,
                    status ENUM('available', 'used', 'expired') DEFAULT 'available',
                    order_id INT DEFAULT NULL,
                    created_at DATETIME,
                    used_at DATETIME,
                    INDEX idx_product (product_id),
                    INDEX idx_status (status),
                    INDEX idx_order (order_id),
                    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'orders' => "
                CREATE TABLE IF NOT EXISTS orders (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    order_no VARCHAR(50) NOT NULL UNIQUE,
                    product_id INT NOT NULL,
                    user_id INT DEFAULT 0,
                    quantity INT DEFAULT 1,
                    total_amount DECIMAL(10,2) NOT NULL,
                    contact_info VARCHAR(500),
                    payment_method VARCHAR(20) DEFAULT 'alipay',
                    status ENUM('pending', 'completed', 'failed', 'cancelled') DEFAULT 'pending',
                    payment_no VARCHAR(100),
                    cdk_code VARCHAR(50),
                    created_at DATETIME,
                    updated_at DATETIME,
                    INDEX idx_order_no (order_no),
                    INDEX idx_status (status),
                    INDEX idx_user (user_id),
                    INDEX idx_created (created_at),
                    INDEX idx_cdk (cdk_code),
                    FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE RESTRICT
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'payment_logs' => "
                CREATE TABLE IF NOT EXISTS payment_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    order_no VARCHAR(50) NOT NULL,
                    payment_no VARCHAR(100),
                    action VARCHAR(20) NOT NULL,
                    amount DECIMAL(10,2),
                    params TEXT,
                    created_at DATETIME,
                    INDEX idx_order (order_no),
                    INDEX idx_action (action),
                    INDEX idx_created (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'cdk_assign_logs' => "
                CREATE TABLE IF NOT EXISTS cdk_assign_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    order_id INT NOT NULL,
                    cdk_code VARCHAR(50) NOT NULL,
                    assigned_at DATETIME,
                    INDEX idx_order (order_id),
                    INDEX idx_cdk (cdk_code),
                    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'users' => "
                CREATE TABLE IF NOT EXISTS users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    email VARCHAR(100),
                    role ENUM('admin', 'user') DEFAULT 'user',
                    status TINYINT DEFAULT 1,
                    created_at DATETIME,
                    last_login DATETIME,
                    INDEX idx_username (username),
                    INDEX idx_role (role)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ",
            
            'system_settings' => "
                CREATE TABLE IF NOT EXISTS system_settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    setting_key VARCHAR(100) NOT NULL UNIQUE,
                    setting_value TEXT,
                    setting_type ENUM('string', 'int', 'float', 'bool', 'json') DEFAULT 'string',
                    description VARCHAR(255),
                    updated_at DATETIME,
                    INDEX idx_key (setting_key)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            "
        ];
    }

    /**
     * 插入初始数据
     */
    public function insertInitialData() {
        // 插入管理员用户
        $adminPassword = password_hash('admin123', PASSWORD_DEFAULT);
        $sql = "INSERT IGNORE INTO users (username, password, email, role, created_at) 
                VALUES ('admin', ?, 'admin@example.com', 'admin', NOW())";
        $stmt = $this->db->prepare($sql);
        $stmt->bind_param("s", $adminPassword);
        $stmt->execute();
        echo "管理员用户创建成功 (用户名: admin, 密码: admin123)\n";

        // 插入示例商品
        $sampleProducts = [
            ['游戏礼包A', '包含稀有道具的游戏礼包', 29.90, 100],
            ['游戏礼包B', '高级游戏礼包', 49.90, 50],
            ['月卡', '30天游戏月卡', 19.90, 200],
            ['新手礼包', '新手专用礼包', 9.90, 300]
        ];

        foreach ($sampleProducts as $product) {
            $sql = "INSERT IGNORE INTO products (name, description, price, stock, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, NOW(), NOW())";
            $stmt = $this->db->prepare($sql);
            $stmt->bind_param("ssdi", $product[0], $product[1], $product[2], $product[3]);
            $stmt->execute();
        }
        echo "示例商品创建成功\n";

        return true;
    }

    /**
     * 运行安装
     */
    public function run() {
        echo "开始安装CDK支付系统...\n";
        echo "==============================\n";

        if (!$this->createDatabase()) {
            return false;
        }

        if (!$this->createTables()) {
            return false;
        }

        if (!$this->insertInitialData()) {
            return false;
        }

        echo "==============================\n";
        echo "安装完成！\n";
        echo "请修改 config/database.php 中的数据库配置信息\n";
        echo "请修改 classes/EasyPay.php 中的易支付配置信息\n";
        echo "管理员登录信息：用户名: admin, 密码: admin123\n";

        return true;
    }
}

// 运行安装
if (php_sapi_name() === 'cli') {
    $installer = new Installer();
    $installer->run();
} else {
    echo "请在命令行中运行此脚本: php install.php\n";
}
